Skip to content

Conversation

@ivansky
Copy link
Contributor

@ivansky ivansky commented May 27, 2025

when store is accessed and injection context is not found it falls back to global active pinia object,

although it is safe for client, on the server side there are could be many requests with their own context,

falling back to global state leads to race conditions and undefined behaviour,

this should be fixed once and for all!

it is probably a breaking change but a good one, I haven't tested this locally, I appreciate any help to improve this PR in order to make it good looking

Summary by CodeRabbit

  • New Features

    • Added public APIs to get and set the active Pinia instance.
  • Tests

    • Added SSR tests validating active-Pinia behavior when called outside a Pinia context.
    • Enhanced console mock utilities to track and assert on both warnings and errors (new error-focused helpers and matchers).
  • Improvements

    • Development-mode diagnostics now warn about potential SSR / cross-request Pinia context issues.

@netlify
Copy link

netlify bot commented May 27, 2025

Deploy Preview for pinia-official canceled.

Name Link
🔨 Latest commit 11be687
🔍 Latest deploy log https://app.netlify.com/projects/pinia-official/deploys/690a1186762ddc00079c7438

*/
export const getActivePinia = () =>
(hasInjectionContext() && inject(piniaSymbol)) || activePinia
(hasInjectionContext() && inject(piniaSymbol)) || (import.meta.server ? throw new Error("Cannot get active pinia as it does not find context") : activePinia)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR. This could be changed into a non breaking change by just showing an error and still returning the active pinia. The error should be in development only (like other warnings) and should not rely on import as it might not work in all scenarios

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think failing fast is the better approach when the global activePinia is accessed on the server, because:

  1. failing immediately makes the problem obvious rather than silently continuing with potentially incorrect behavior.
  2. allowing it to continue by returning activePinia could lead to dangerous state sharing between requests, which is particularly problematic in server environments.

maybe making the message is more clear would help huge

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That would be a breaking change. Also, I do prefer the error message because it feels less frustrating to users

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will leave the decision to you,

However, please keep in mind that the developers tend to ignore error messages, so they will make the same mistakes again and again, I would prefer it to fail that will indicate the mistake much faster.

@ivansky
Copy link
Contributor Author

ivansky commented May 27, 2025

@posva I removed throwing error, added console.error and fallback to createPinia() instead, please check.

@github-project-automation github-project-automation bot moved this to 🆕 Triaging in Pinia Roadmap Jun 3, 2025
@posva posva moved this from 🆕 Triaging to 💬 In discussion in Pinia Roadmap Jun 3, 2025
@posva posva changed the title fix: never use global context on the server side feat(warn): detect global context on the server side Jul 1, 2025
@iPrytz
Copy link

iPrytz commented Oct 14, 2025

Perfect @ivansky ! This would be great to have at least a warning. Would also have preferred the throw error but anything is better than nothing.

@posva posva moved this from 💬 In discussion to 📋 Backlog in Pinia Roadmap Nov 3, 2025
@posva posva moved this from 📋 Backlog to 🧑‍💻 In progress in Pinia Roadmap Nov 4, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 4, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

Adds exported getActivePinia() and setActivePinia() to the Pinia public API, generalizes test console mocks to support both warn and error, and updates server-side getActivePinia() to emit a dev-mode console error when invoked outside a Pinia context on the server.

Changes

Cohort / File(s) Summary
Public API exports
packages/pinia/src/index.ts
Exported new functions getActivePinia() and setActivePinia(pinia).
Root store runtime check
packages/pinia/src/rootStore.ts
Imported IS_CLIENT; updated getActivePinia() to emit a development-mode console error when no Pinia is injected and running off‑client (server), preserving existing fallback to activePinia.
Test mock utilities
packages/pinia/__tests__/vitest-mock-warn.ts
Reworked mock helper into createMockConsoleMethod(method) to support 'warn' and 'error'; added mockConsoleError() and matcher augmentations for errored assertions.
SSR tests
packages/pinia/__tests__/ssr.spec.ts
Imported getActivePinia/setActivePinia; integrated mockWarn and mockConsoleError; added tests asserting error/warning when getActivePinia() is called outside Pinia context.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Env
    participant API as getActivePinia()
    participant Inject as Injection Context
    participant Fallback as activePinia
    participant Console as console.error / console.warn

    Test->>API: call getActivePinia()
    API->>Inject: read injected pinia
    alt injected pinia exists
        API->>Test: return injected pinia
    else no injected pinia
        alt not IS_CLIENT and __DEV__
            API->>Console: emit dev-mode error (cross-request risk)
        end
        API->>Fallback: return activePinia (could be undefined)
        API->>Test: return fallback result
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Check getActivePinia() dev-mode server condition and message correctness.
  • Verify new exports in src/index.ts match typings and are exported from package entrypoints.
  • Confirm createMockConsoleMethod correctly restores console state and that new matchers behave as intended.

Possibly related PRs

Poem

🐇 I hopped through tests at break of day,

Found warnings where the Pinia slipped away,
I mocked the noise and set the scene,
Now errors and warns are neatly seen,
A rabbit's cheer for clearer Pinia play.

Pre-merge checks and finishing touches

✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding detection of global context usage on the server side. It accurately reflects the core objective of preventing server-side fallback to global Pinia state.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4bcc07a and 11be687.

📒 Files selected for processing (2)
  • packages/pinia/__tests__/ssr.spec.ts (2 hunks)
  • packages/pinia/src/rootStore.ts (2 hunks)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Nov 4, 2025

Open in StackBlitz

npm i https://pkg.pr.new/@pinia/nuxt@2983
npm i https://pkg.pr.new/pinia@2983
npm i https://pkg.pr.new/@pinia/testing@2983

commit: 4bcc07a

@codecov
Copy link

codecov bot commented Nov 4, 2025

Codecov Report

❌ Patch coverage is 76.92308% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.16%. Comparing base (8a65eb7) to head (4bcc07a).

Files with missing lines Patch % Lines
packages/pinia/src/rootStore.ts 76.92% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##               v3    #2983      +/-   ##
==========================================
- Coverage   91.28%   91.16%   -0.13%     
==========================================
  Files          18       18              
  Lines        1618     1629      +11     
  Branches      231      235       +4     
==========================================
+ Hits         1477     1485       +8     
- Misses        139      142       +3     
  Partials        2        2              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
packages/pinia/__tests__/vitest-mock-warn.ts (1)

19-121: Excellent refactoring!

The generalization of the mock infrastructure to support both warn and error methods is well-executed:

  • Dynamic matcher name generation is correct for both methods
  • All assertion logic (basic, last, times) properly adapted
  • Unasserted log detection and error reporting maintained
  • Eliminates code duplication while preserving functionality
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8a65eb7 and 4bcc07a.

📒 Files selected for processing (3)
  • packages/pinia/__tests__/ssr.spec.ts (2 hunks)
  • packages/pinia/__tests__/vitest-mock-warn.ts (1 hunks)
  • packages/pinia/src/rootStore.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
packages/pinia/__tests__/ssr.spec.ts (2)
packages/pinia/__tests__/vitest-mock-warn.ts (2)
  • mockWarn (123-125)
  • mockConsoleError (127-129)
packages/pinia/src/rootStore.ts (2)
  • setActivePinia (35-35)
  • getActivePinia (51-65)
packages/pinia/src/rootStore.ts (3)
packages/pinia/src/index.ts (2)
  • getActivePinia (4-4)
  • Pinia (6-6)
rollup.config.mjs (1)
  • __DEV__ (166-171)
packages/pinia/src/env.ts (1)
  • IS_CLIENT (1-1)
🔇 Additional comments (6)
packages/pinia/__tests__/ssr.spec.ts (2)

5-11: LGTM!

The imports correctly reflect the newly exposed public API functions.


16-16: LGTM!

The mock setup correctly initializes both warn and error tracking for the test suite, ensuring proper assertion of console output from getActivePinia.

Also applies to: 19-20

packages/pinia/src/rootStore.ts (2)

20-20: LGTM!

The IS_CLIENT import is correctly used to detect server-side execution at line 55.


43-47: The review comment is incorrect.

The ImportMeta.server declaration is actively used in the codebase (packages/nuxt/playground/pages/index.vue:12: if (import.meta.server)). This global type augmentation is necessary for TypeScript type safety when accessing import.meta.server. Removing it would cause TypeScript compilation errors.

Likely an incorrect or invalid review comment.

packages/pinia/__tests__/vitest-mock-warn.ts (2)

9-11: LGTM!

The type definitions correctly extend the matcher API to support error assertions, mirroring the existing warn matchers.


123-129: LGTM!

The exported functions provide a clean public API for test setup, properly delegating to the generic implementation.

posva and others added 2 commits November 4, 2025 15:45
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@posva posva merged commit be9e356 into vuejs:v3 Nov 4, 2025
4 checks passed
@github-project-automation github-project-automation bot moved this from 🧑‍💻 In progress to ✅ Done in Pinia Roadmap Nov 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: ✅ Done

Development

Successfully merging this pull request may close these issues.

3 participants